#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use lib qw(libs);
require "parse_excel.pl";
# use JSON();
use JSON::Syck();

binmode STDOUT, ":utf8";
binmode STDERR, ":utf8";

my $EXCEL = $ARGV[0];
my $JSON  = $ARGV[1];

unless ($EXCEL) {
    die "Usage: $0 source.xls out.json"
}
unless ($JSON) {
    $JSON = $EXCEL;
    $JSON =~ s:[^/\.]+$:json:;
}

main();

sub main {
    my $data = excel2json();
    # my $json = JSON->new->pretty->encode($data);
    my $json = JSON::Syck::Dump($data);
    save($JSON, $json);
    my $jsonp = 'apple_table_loaded('.$json.');';
    save($JSON.'p', $jsonp);
}

sub excel2json {
    info("<<<<", $EXCEL);
    my($tables, $names) = parse_excel::parse_excel($EXCEL);
    die "Invalid data: $EXCEL\n" unless ref $tables;

    my $data = {};
    while(scalar @$tables) {
        my $name1  = shift @$names;
        $name1 ||= 1 + scalar keys %$data;
        info('----', $name1);
        my $sheet1 = shift @$tables;
        my $head = shift @$sheet1;
        my $list = [];
        foreach my $row (@$sheet1) {
            my %hash;
            next unless scalar grep {defined $_ && $_ ne ''} @$row;
            foreach my $key (@$head) {
                my $val = shift @$row;
                next unless defined $key;
                next unless defined $val;
                next if ($val eq '');
                $hash{$key} = $val;
            }
            push(@$list, \%hash);
        }
        $data->{$name1} = $list;
    }
    die "Null data: $EXCEL\n" unless scalar keys %$data;
    $data;
}

sub save {
    my $file = shift;
    my $buf  = shift;
    info(">>>>", $file);
    open(OUT, ">", $file) or die "$! - $file\n";
    binmode OUT, ":utf8";
    print OUT (ref $buf) ? @$buf : $buf;
    close(OUT);
}

sub info {
    local $, = " ";
    print STDERR @_, "\n";
}
